//
//  ChangePsdViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/13.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "ChangePsdViewController.h"

@interface ChangePsdViewController ()
{
    UITextField *txtPsd;
    UITextField *txtNewPsd;
    UITextField  *txtNewPsdAgain;
}
@end

@implementation ChangePsdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = EastMarket_backgroundColor;
    self.title = @"修改密码";
    [self initChangePsdUI];
}

- (void)initChangePsdUI {

    CGFloat spacing = 8.0f;
    CGFloat border = 1.0f;
    // 背景ScrollView
    UIScrollView *applicationSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    applicationSV.showsVerticalScrollIndicator = YES;
    applicationSV.showsVerticalScrollIndicator = NO;
    applicationSV.backgroundColor = [UIColor clearColor];
    applicationSV.delegate = self;
    applicationSV.scrollEnabled = YES;
    [self.view addSubview:applicationSV];
    
    applicationSV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapapplicationSV = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyBoard:)];
    [applicationSV addGestureRecognizer:tapapplicationSV];
    
    UIView *viewPsdInfo = [[UIView alloc]initWithFrame:CGRectMake(0, spacing * 3, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
    viewPsdInfo.layer.cornerRadius = 3.0;
    viewPsdInfo.backgroundColor = [UIColor whiteColor];
    [applicationSV addSubview:viewPsdInfo];
    
    // Old Psd
    UILabel *lblPsd = [[UILabel alloc]initWithFrame:CGRectMake(spacing, 0, (SCREEN_WIDTH - 2 * spacing) / 4, viewPsdInfo.frame.size.height / 3)];
    lblPsd.text = @"旧  密  码";
    lblPsd.textColor = [UIColor blackColor];
    lblPsd.textAlignment = NSTextAlignmentLeft;
    lblPsd.font = [UIFont systemFontOfSize:16];
    
    txtPsd = [self createTextFielfFrame:CGRectMake(lblPsd.frame.origin.x + lblPsd.frame.size.width + spacing, lblPsd.frame.origin.y, viewPsdInfo.frame.size.width - 3 * spacing - lblPsd.frame.size.width, lblPsd.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"请输入旧密码"];
    txtPsd.textAlignment = NSTextAlignmentRight;
    //    [txtInsureName setTextColor:[UIColor blackColor]];
    txtPsd.delegate = self;
    txtPsd.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIImageView *line1=[self createImageViewFrame:CGRectMake(lblPsd.frame.origin.x, lblPsd.frame.origin.y + lblPsd.frame.size.height - border, viewPsdInfo.frame.size.width - 2 * spacing, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // New PSd
    UILabel *lblNewPsd = [[UILabel alloc] initWithFrame:CGRectMake(lblPsd.frame.origin.x, lblPsd.frame.origin.y + lblPsd.frame.size.height, lblPsd.frame.size.width, lblPsd.frame.size.height)];
    lblNewPsd.text = @"新  密  码";
    lblNewPsd.textColor = [UIColor blackColor];
    lblNewPsd.textAlignment = NSTextAlignmentLeft;
    lblNewPsd.font = [UIFont systemFontOfSize:16];
    
    txtNewPsd = [self createTextFielfFrame:CGRectMake(txtPsd.frame.origin.x, lblNewPsd.frame.origin.y, txtPsd.frame.size.width, lblNewPsd.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"请输入新密码"];
    txtNewPsd.textAlignment = NSTextAlignmentRight;
    txtNewPsd.delegate = self;
    txtNewPsd.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIImageView *line2=[self createImageViewFrame:CGRectMake(line1.frame.origin.x, lblNewPsd.frame.origin.y + lblNewPsd.frame.size.height - border, line1.frame.size.width, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // New Psd Again
    UILabel *lblNewPsdAgain = [[UILabel alloc] initWithFrame:CGRectMake(lblNewPsd.frame.origin.x, lblNewPsd.frame.origin.y + lblNewPsd.frame.size.height, lblNewPsd.frame.size.width, lblNewPsd.frame.size.height)];
    lblNewPsdAgain.text = @"确认密码";
    lblNewPsdAgain.textColor = [UIColor blackColor];
    lblNewPsdAgain.textAlignment = NSTextAlignmentLeft;
    lblNewPsdAgain.font = [UIFont systemFontOfSize:16];
    
    txtNewPsdAgain = [self createTextFielfFrame:CGRectMake(txtNewPsd.frame.origin.x, lblNewPsdAgain.frame.origin.y, txtNewPsd.frame.size.width, txtNewPsd.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"请输入确认密码"];
    txtNewPsdAgain.textAlignment = NSTextAlignmentRight;
    //    [txtInsureGender setTextColor:[UIColor blackColor]];
    txtNewPsdAgain.delegate = self;
    txtNewPsdAgain.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    [viewPsdInfo addSubview:lblPsd];
    [viewPsdInfo addSubview:txtPsd];
    [viewPsdInfo addSubview:line1];
    
    [viewPsdInfo addSubview:lblNewPsd];
    [viewPsdInfo addSubview:txtNewPsd];
    [viewPsdInfo addSubview:line2];
    
    [viewPsdInfo addSubview:lblNewPsdAgain];
    [viewPsdInfo addSubview:txtNewPsdAgain];
    
    // 底部View
    UIView *viewBottom = [[UIView alloc] initWithFrame:CGRectMake(0, viewPsdInfo.frame.origin.y + viewPsdInfo.frame.size.height + 32, SCREEN_WIDTH, 49)];
    viewBottom.backgroundColor = [UIColor clearColor];
    [applicationSV addSubview:viewBottom];
    
    UIButton *btnConfirm = [UIButton buttonWithType:UIButtonTypeSystem];
    btnConfirm.frame = CGRectMake(16 * 2, 4, viewBottom.frame.size.width - 16 * 4, viewBottom.frame.size.height - 2 * 4);
    btnConfirm.backgroundColor = EastMarket_MainToneColor;
    [btnConfirm setTitle:@"确认" forState:UIControlStateNormal];
    [btnConfirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnConfirm.titleLabel setFont:[UIFont systemFontOfSize:18]];
    btnConfirm.layer.cornerRadius = 5.0f;
    [btnConfirm addTarget:self action:@selector(btnConfirmClicked:) forControlEvents:UIControlEventTouchUpInside];
    [viewBottom addSubview:btnConfirm];
    
    applicationSV.contentSize = CGSizeMake(SCREEN_WIDTH, viewBottom.frame.origin.y + viewBottom.frame.size.height + TopBarHeight + TabBarHeight);
}

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    textField.font=font;
    textField.textColor=[UIColor grayColor];
    textField.borderStyle=UITextBorderStyleNone;
    textField.placeholder=placeholder;
    
    return textField;
}

-(UITextView *)createTextViewfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextView *textView=[[UITextView alloc]initWithFrame:frame];
    textView.font=font;
    textView.textColor=[UIColor grayColor];
    
    return textView;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

- (void)hidenKeyBoard:(UIGestureRecognizer *)tap {

    [txtPsd resignFirstResponder];
    [txtNewPsd resignFirstResponder];
    [txtNewPsdAgain resignFirstResponder];
}

- (void)btnConfirmClicked:(UIButton *)btn {

    debugMethod();
//    [self loadUpdateMemberInfo];
    [self loadViewModifyPassword];
}

- (void)loadViewModifyPassword {

    if ([GlobalUnit isBlankString:txtPsd.text]) {
        [GlobalUnit showPopHint:@"请输入原始密码" targetView:txtPsd showInView:self.view];
        return;
    }
    if ([GlobalUnit isBlankString:txtNewPsd.text]) {
        [GlobalUnit showPopHint:@"请输入新密码" targetView:txtNewPsd showInView:self.view];
        return;
    }
    if ([GlobalUnit isBlankString:txtNewPsdAgain.text]) {
        [GlobalUnit showPopHint:@"请输再次入新密码" targetView:txtNewPsdAgain showInView:self.view];
        return;
    }
    if (![txtNewPsd.text isEqualToString:txtNewPsdAgain.text]) {
        [GlobalUnit showPopHint:@"两次输入密码不一样" targetView:txtNewPsdAgain showInView:self.view];
        return;
    }
    
    [NSThread detachNewThreadSelector:@selector(callServerModifyPassword) toTarget:self withObject:Nil];
}

- (void)callServerModifyPassword {

    NSDictionary *resultOfModifyPassword = [AppServiceInterface ModifyPassword:txtPsd.text password:txtNewPsd.text];
    [self performSelectorOnMainThread:@selector(updateUIAfterModifyPwd:) withObject:resultOfModifyPassword waitUntilDone:true];
}

-(void)updateUIAfterModifyPwd:(NSDictionary *)dic {
    
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        NSString *showMsg = @"恭喜你修改密码成功";
        if ([[dic objectForKey:@"msg"] isKindOfClass:[NSNull class]]) {
            showMsg = [NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]];
        }
        [GlobalUnit showMessage:[NSString stringWithFormat:@"%@", showMsg]];
        [self.navigationController popViewControllerAnimated:true];
    } else if (dic && [[dic objectForKey:@"success"] integerValue] == 0) {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}

- (void)loadUpdateMemberInfo {
    
    [NSThread detachNewThreadSelector:@selector(callServerUpdateMemberInfo) toTarget:self withObject:Nil];
}
- (void)callServerUpdateMemberInfo {
    
    NSDictionary *dic = [AppServiceInterface GetCurrentAccountInfo];
    [self performSelectorOnMainThread:@selector(updateCurrentAccountRankUI:) withObject:dic waitUntilDone:NO];
}

- (void)updateCurrentAccountRankUI:(NSDictionary *)dict {
    if (dict &&  [[dict objectForKey:@"success"] integerValue] == 1) {
        debugLog(@"%@", dict);
        NSNotification *notice = [NSNotification notificationWithName:NotificationLoginSccess object:nil];
        [[NSNotificationCenter defaultCenter] postNotification:notice];
        [self.navigationController popViewControllerAnimated:true];
    }
    else {
        [GlobalUnit showAlertHint:@"温馨提示" message:[dict objectForKey:@"message"]];
    }
}

#pragma mark -- UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    [textField resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldFrame      = textField.frame;
    //当前输入框的Y
    CGFloat textField_Y        = textFieldFrame.origin.y;
    //当前输入框的高度
    CGFloat textFieldHight     = textFieldFrame.size.height;
    //屏幕高度
    CGFloat screenHight        = self.view.frame.size.height;
    //键盘高度
    //    CGFloat keyBordHight       = keyBordHight;
    //键盘tabbar高度
    CGFloat keyBordTabbarHight = 49;
    //计算输入框向上移动的偏移量
    int offset = textField_Y + textFieldHight + 64 - (screenHight - KeyboardHeight - keyBordTabbarHight);
    
    //根据键盘遮挡的高度开始移动动画
    [UIView animateWithDuration:0.3 animations:^{
        if (offset > 0) {
            
            float width = self.view.frame.size.width;
            float hight = self.view.frame.size.height;
            
            CGRect rect = CGRectMake(0, -offset, width, hight);
            self.view.frame = rect;
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    //键盘收回后视图移动回原位的动画
    [UIView animateWithDuration:0.3 animations:^{
        
        float width = self.view.frame.size.width;
        float hight = self.view.frame.size.height;
        
        CGRect rect = CGRectMake(0, 44 + 20, width, hight);
        self.view.frame = rect;
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    //点击Return,键盘收回后视图移动回原位的动画
    [UIView animateWithDuration:0.3 animations:^{
        
        float width = self.view.frame.size.width;
        float hight = self.view.frame.size.height;
        
        CGRect rect = CGRectMake(0, 44 + 20, width, hight);
        self.view.frame = rect;
    }];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
